package com.bss.utils;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.andy.basics.AbstractMap;
import com.andy.basics.ClassMapper;
import com.andy.basics.Entity;

@Component
public class TopFinder extends AbstractMap {

	private static final String CLASS = TopFinder.class.getName();

	private static final Logger LOGGER = Logger.getLogger(TopFinder.CLASS);

	@Autowired
	private ClassMapper classMapper;

	@PersistenceContext
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return this.entityManager;
	}

	public void setClassMapper(final ClassMapper classMapper) {
		this.classMapper = classMapper;
	}

	public ClassMapper getClassMapper() {
		return this.classMapper;
	}

	/**
	 * Returns the top n elements from a table. The argument must be a comma
	 * separated string in which: The 1st argument is the model name The 2nd
	 * argument is the field name on which the data will be sorted The 3rd
	 * argument is the value of n as an Integer e.g. admission,dateOfExit,10
	 */
	@Override
	public List<Entity> get(final Object key) {

		String[] args = key.toString().split(",");

		String queryString = "from " + this.getClassMapper().map(args[0]).getName() + " as table1 where table1." + args[1]
				+ " is not null order by table1." + args[1] + " desc";
		Query query = this.getEntityManager().createQuery(queryString);

		query.setMaxResults(Integer.parseInt(args[2]));

		List<Entity> list = null;

		try {
			list = query.getResultList();
		} catch (Exception e) {

			TopFinder.LOGGER.error("Query: " + "\nError Message: " + e.getMessage(), e);
		}
		return list;

	}
}
